#include "reg51.h"
#include "Driver_74HC595.h"
#include "OP_EEPROM.h"
#include "intrins.h"

/*
 今天吃什么？
*/

// 几个50毫秒后休眠
#define SLEEP_TIME 300
sfr P3M0 = 0xb2;
sfr P3M1 = 0xb1;

sbit P30 = P3^0;
sbit P31 = P3^1;
sbit P32 = P3^2;
sbit P33 = P3^3;

sfr P5   = 0xC8;
sbit P55 = P5^5;
sbit P54 = P5^4;

sfr INTCLKO = 0x8f;
sfr AUXINTIF = 0xef;
sfr AUXR = 0x8e;
int timesL, timesR;
char out;
int sleepTimer;
void Delay500ms()		//@12.000MHz
{
	unsigned char i, j, k;

	_nop_();
	_nop_();
	i = 23;
	j = 205;
	k = 120;
	do
	{
		do
		{
			while (--k);
		} while (--j);
	} while (--i);
}

void Delay5ms()		//@12.000MHz
{
	unsigned char i, j;

	i = 59;
	j = 90;
	do
	{
		while (--j);
	} while (--i);
}

void Timer0Init(void)		//50毫秒@12.000MHz
{
	AUXR &= 0x7F;		//定时器时钟12T模式
	TMOD &= 0xF0;		//设置定时器模式
	TL0 = 0xB0;		//设置定时初始值
	TH0 = 0x3C;		//设置定时初始值
	TF0 = 0;		//清除TF0标志
	ET0 = 1;		//允许中断
	TR0 = 1;		//定时器0开始计时
}

void Timer1Init(void){ //用于生成随机数
	AUXR |= 0x40;		//1T模式
	TMOD &= 0x0F;		//设置定时器模式
	TL1 = 0x00;
	TH1 = 0x00;
	TF1 = 0;
	ET1 = 0; //禁止中断
	TR1 = 1;
}

void main(){
	int stayTimes;
	P3M0 = 0;
	P3M1 = 0;
	out = 0x01;
	INTCLKO |= 0x30; //使能INT2/INT3中断（仅下降沿）
	EX1 = 1;
	EA = 1;
	Timer0Init();
	Timer1Init();
	for(;;){
		WriteAndFlushByte595(out);
		if(P54 != 1 || P55 != 1){
			for(;;){
				if (P54 == 1 && P55 == 1){
					stayTimes++;
					if (stayTimes == 100){
						break;
					}
				} else {
					stayTimes = 0;
				}
			}
		}
		AUXINTIF &= 0xcf; // 清空INT2中断
		INTCLKO |= 0x30; //使能INT2/INT3中断（仅下降沿）
	}
}

void onclick() interrupt 2{
	unsigned char dat[4];
	// 暂时用于测试IAP
	READ_EEPROM(0x18, 4, dat);
	WriteAndFlushByte595(dat[0]);
	Delay500ms();
	WriteAndFlushByte595(dat[1]);
	Delay500ms();
	WriteAndFlushByte595(dat[2]);
	Delay500ms();
	WriteAndFlushByte595(dat[3]);
	Delay500ms();
	//
	timesL = 0;
	timesR = 0;
	sleepTimer = 0;
}

void onLeft() interrupt 10{
	char randNum;
	INTCLKO &= 0xCF; //关闭INT2/INT3中断
	randNum = TL1 % 8;
	out = 0x01 << randNum;
	sleepTimer = 0;
}

void onRight() interrupt 11{
	char randNum;
	INTCLKO &= 0xCF; //关闭INT2/INT3中断
	randNum = TL1 % 8;
	out = 0x01 << randNum;
	sleepTimer = 0;
}

void onTimer0() interrupt 1{
	if (sleepTimer >= SLEEP_TIME){
		WriteAndFlushByte595(0x00); // 关闭所有LED
		PCON |= 0x02;
		_nop_();
		_nop_();
		_nop_();
		_nop_();
		sleepTimer = 0;
	} else {
		sleepTimer++;
	}
}